package net.dopan.pigframe.config.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.net.URL;


/**
 * @author wufeihong 根据经纬度获取  省市区
 */
public class LocationUtils {

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     *
     *  参数解释: 纬度,经度
     * @param longitude
     * @param latitude
     * @return
     */
    public static String[] getAdd(String longitude, String latitude ){

        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+latitude+","+longitude+"&type=010";
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }

        JSONObject jsonObject = JSONObject.fromObject(res);
        JSONArray jsonArray = JSONArray.fromObject(jsonObject.getString("addrList"));
        JSONObject j_2 = JSONObject.fromObject(jsonArray.get(0));
        System.out.println(j_2);
        String allAdd = j_2.getString("admName");
        String[] arr = allAdd.split(",");
        return arr;
    }

    /**
     * 通过经纬度获取距离(单位：km)
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static Double getDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        return Double.parseDouble(String.format("%.1f", s));
    }

    public static void main(String[] args) {
        String arr[] = getAdd("120.54", "30.64");
        System.out.println("省:province"+arr[0]+"\n市:city"+arr[1]+"\n区:area"+arr[2]);
       String str =  getDistance(29.88,121.55,121.55,29.87)+"";
        System.err.println(str);
    }
}
